package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.profix}")
    String profix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.参数校验
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.上传到oss
        String fileId = null;
        try {
            String fileName = UUID.randomUUID().toString().replace("-", "");
            //图片名称
            String originalFilename = multipartFile.getOriginalFilename();
            //得到图片后缀名
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //上传图片
            fileId = fileStorageService.store(profix, fileName + postfix, multipartFile.getInputStream());
            log.info("filed:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("WmMaterialServiceImpl-文件上传失败");
        }

        //3.保存到素材表中
        WmMaterial material = new WmMaterial();
        material.setCreatedTime(new Date());
        material.setIsCollection((short)0);
        material.setUrl(fileId);
        material.setUserId(user.getId());
        material.setType((short)0);
        save(material);

        //前端展示
        material.setUrl(webSite+fileId);

        //4.结果返回
        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //判断参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //分页查询

        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //根据收藏查询
        if (dto.getIsCollection()!=null||dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        IPage page = new Page(dto.getPage(),dto.getSize());
        page=page(page,wrapper);
        //图片处理
        List records = page.getRecords();
        //图片处理
        List<WmMaterial> wmMaterials = page.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(wmMaterials);

        return responseResult;
    }
@Autowired
private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {

        //判断参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询是否关联
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer count=wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId,id));

       if (count>0){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材被引用，不能删除");
       }
        //根据素材图片地址删除阿里云的图片
        fileStorageService.delete(wmMaterial.getUrl());
      removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short collectMaterial) {
        //检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //因为携带token,所以需要用到线程
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //根据id进行修改
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getType,collectMaterial)
        .eq(WmMaterial::getUserId,uid)
        .eq(WmMaterial::getId,id));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}